// unit.js
Page({
  data: {
    unitId: '',
    unitName: '单词学习',
    currentWordIndex: 0,
    totalWords: 0,
    learningMode: 'match', // match: 图片配对, puzzle: 拼图游戏, pronunciation: 发音挑战
    currentWord: {},
    words: [],
    selectedImageOption: -1,
    shuffledLetters: [],
    puzzleAnswers: [],
    showSuccessModal: false,
    cardAnimation: {},
    recording: false
  },

  onLoad(options) {
    const { id, name } = options;
    
    this.setData({
      unitId: id,
      unitName: decodeURIComponent(name || '单词学习')
    });
    
    // 加载单词数据
    this.loadWordData();
    
    // 初始化动画
    this.initAnimation();
  },

  // 加载单词数据
  loadWordData() {
    // 模拟单词数据
    const wordData = this.getMockWordData(this.data.unitId);
    
    this.setData({
      words: wordData,
      totalWords: wordData.length,
      currentWord: wordData[0]
    });
    
    // 根据学习模式初始化游戏数据
    this.initGameData();
  },

  // 初始化动画
  initAnimation() {
    const animation = wx.createAnimation({
      duration: 300,
      timingFunction: 'ease'
    });
    
    this.setData({
      cardAnimation: animation.export()
    });
    
    this.animation = animation;
  },

  // 初始化游戏数据
  initGameData() {
    const { currentWord, learningMode } = this.data;
    
    if (learningMode === 'match') {
      this.setData({
        selectedImageOption: -1
      });
    } else if (learningMode === 'puzzle') {
      // 打乱字母顺序
      const letters = currentWord.english.toUpperCase().split('');
      const shuffled = [...letters].sort(() => Math.random() - 0.5);
      
      this.setData({
        shuffledLetters: shuffled,
        puzzleAnswers: Array(letters.length).fill('')
      });
    } else if (learningMode === 'pronunciation') {
      this.setData({
        selectedPronunciationOption: -1
      });
    }
  },

  // 切换学习模式
  changeLearningMode(e) {
    const mode = e.detail.value;
    
    this.setData({
      learningMode: mode,
      selectedImageOption: -1,
      selectedPronunciationOption: -1
    });
    
    // 初始化新学习模式的游戏数据
    this.initGameData();
  },

  // 播放单词发音
  playPronunciation() {
    // 实际项目中应该调用语音播放API
    wx.showToast({
      title: '播放单词发音',
      icon: 'none'
    });
    
    // 简单的动画效果
    this.animation.scale(1.05).step().scale(1).step();
    this.setData({
      cardAnimation: this.animation.export()
    });
  },

  // 选择图片选项（图片配对游戏）
  selectImageOption(e) {
    const index = e.currentTarget.dataset.index;
    const { currentWord } = this.data;
    
    this.setData({
      selectedImageOption: index
    });
    
    // 检查答案是否正确
    const isCorrect = index === 0; // 假设第一个是正确答案
    
    if (isCorrect) {
      wx.showToast({
        title: '太棒了！正确！',
        icon: 'success'
      });
      
      // 简单的动画效果
      this.animation.scale(1.1).step().scale(1).step();
      this.setData({
        cardAnimation: this.animation.export()
      });
    } else {
      wx.showToast({
        title: '再试一次吧！',
        icon: 'none'
      });
    }
  },

  // 选择字母（拼图游戏）
  selectLetter(e) {
    const letter = e.currentTarget.dataset.letter;
    const { puzzleAnswers } = this.data;
    
    // 找到第一个空位置
    const emptyIndex = puzzleAnswers.findIndex(answer => answer === '');
    
    if (emptyIndex !== -1) {
      const newAnswers = [...puzzleAnswers];
      newAnswers[emptyIndex] = letter;
      
      this.setData({
        puzzleAnswers: newAnswers
      });
      
      // 检查是否完成拼图
      const isComplete = newAnswers.every(answer => answer !== '');
      
      if (isComplete) {
        // 检查答案是否正确
        const answerString = newAnswers.join('');
        const isCorrect = answerString === this.data.currentWord.english.toUpperCase();
        
        if (isCorrect) {
          wx.showToast({
            title: '拼图完成！真棒！',
            icon: 'success'
          });
          
          // 简单的动画效果
          this.animation.scale(1.1).step().scale(1).step();
          this.setData({
            cardAnimation: this.animation.export()
          });
        } else {
          wx.showToast({
            title: '拼写不正确，再试一次！',
            icon: 'none'
          });
        }
      }
    }
  },

  // 听单词发音（发音挑战游戏）
  listenForPronunciation() {
    wx.showToast({
      title: '播放单词发音...',
      icon: 'none'
    });
  },

  // 选择发音选项
  selectPronunciationOption(e) {
    const index = e.currentTarget.dataset.index;
    
    this.setData({
      selectedPronunciationOption: index
    });
    
    // 检查答案是否正确（假设第一个是正确答案）
    const isCorrect = index === 0;
    
    if (isCorrect) {
      wx.showToast({
        title: '发音真标准！',
        icon: 'success'
      });
    } else {
      wx.showToast({
        title: '再接再厉！',
        icon: 'none'
      });
    }
  },

  // 开始录音（跟读练习）
  startRecording() {
    if (this.data.recording) {
      // 停止录音
      wx.stopRecord();
      this.setData({ recording: false });
      
      wx.showToast({
        title: '录音完成，正在分析...',
        icon: 'none'
      });
      
      // 模拟分析结果
      setTimeout(() => {
        wx.showToast({
          title: '你的发音真棒！',
          icon: 'success'
        });
      }, 1000);
    } else {
      // 开始录音
      this.setData({ recording: true });
      
      wx.startRecord({
        success: (res) => {
          const tempFilePath = res.tempFilePath;
          // 实际项目中应该上传录音文件进行分析
        },
        fail: (err) => {
          console.error('录音失败', err);
          this.setData({ recording: false });
        }
      });
      
      // 10秒后自动停止录音
      setTimeout(() => {
        if (this.data.recording) {
          wx.stopRecord();
          this.setData({ recording: false });
          
          wx.showToast({
            title: '录音超时，已自动停止',
            icon: 'none'
          });
        }
      }, 10000);
    }
  },

  // 上一个单词
  previousWord() {
    if (this.data.currentWordIndex > 0) {
      const newIndex = this.data.currentWordIndex - 1;
      
      this.setData({
        currentWordIndex: newIndex,
        currentWord: this.data.words[newIndex]
      });
      
      // 重新初始化游戏数据
      this.initGameData();
      
      // 简单的动画效果
      this.animation.translateX(-50).opacity(0).step().translateX(0).opacity(1).step();
      this.setData({
        cardAnimation: this.animation.export()
      });
    }
  },

  // 下一个单词
  nextWord() {
    if (this.data.currentWordIndex < this.data.totalWords - 1) {
      const newIndex = this.data.currentWordIndex + 1;
      
      this.setData({
        currentWordIndex: newIndex,
        currentWord: this.data.words[newIndex]
      });
      
      // 重新初始化游戏数据
      this.initGameData();
      
      // 简单的动画效果
      this.animation.translateX(50).opacity(0).step().translateX(0).opacity(1).step();
      this.setData({
        cardAnimation: this.animation.export()
      });
    } else {
      // 完成整个单元
      this.setData({
        showSuccessModal: true
      });
      
      // 学习完成
    }
  },

  // 关闭成功弹窗
  closeSuccessModal() {
    this.setData({
      showSuccessModal: false
    });
    
    // 返回上一页
    wx.navigateBack();
  },

  // 获取模拟单词数据
  getMockWordData(unitId) {
    // 根据单元ID返回不同的单词数据
    const wordDataMap = {
      '1': [
        {
          word: 'lion',
          phonetic: 'ˈlaɪən',
          meaning: '狮子',
          example: 'The lion is the king of the jungle.',
          image: 'https://example.com/lion.jpg',
          imageOptions: ['https://example.com/lion.jpg', 'https://example.com/tiger.jpg', 'https://example.com/elephant.jpg', 'https://example.com/monkey.jpg'],
          pronunciationOptions: [
            { image: 'https://example.com/lion.jpg', word: 'lion' },
            { image: 'https://example.com/tiger.jpg', word: 'tiger' },
            { image: 'https://example.com/elephant.jpg', word: 'elephant' },
            { image: 'https://example.com/monkey.jpg', word: 'monkey' }
          ]
        },
        {
          word: 'tiger',
          phonetic: 'ˈtaɪɡər',
          meaning: '老虎',
          example: 'The tiger has black stripes.',
          image: 'https://example.com/tiger.jpg',
          imageOptions: ['https://example.com/tiger.jpg', 'https://example.com/lion.jpg', 'https://example.com/elephant.jpg', 'https://example.com/monkey.jpg'],
          pronunciationOptions: [
            { image: 'https://example.com/tiger.jpg', word: 'tiger' },
            { image: 'https://example.com/lion.jpg', word: 'lion' },
            { image: 'https://example.com/elephant.jpg', word: 'elephant' },
            { image: 'https://example.com/monkey.jpg', word: 'monkey' }
          ]
        },
        {
          word: 'elephant',
          phonetic: 'ˈelɪfənt',
          meaning: '大象',
          example: 'The elephant has a long trunk.',
          image: 'https://example.com/elephant.jpg',
          imageOptions: ['https://example.com/elephant.jpg', 'https://example.com/lion.jpg', 'https://example.com/tiger.jpg', 'https://example.com/monkey.jpg'],
          pronunciationOptions: [
            { image: 'https://example.com/elephant.jpg', word: 'elephant' },
            { image: 'https://example.com/lion.jpg', word: 'lion' },
            { image: 'https://example.com/tiger.jpg', word: 'tiger' },
            { image: 'https://example.com/monkey.jpg', word: 'monkey' }
          ]
        }
      ],
      '2': [
        {
          word: 'apple',
          phonetic: 'ˈæpl',
          meaning: '苹果',
          example: 'I eat an apple every day.',
          image: 'https://example.com/apple.jpg',
          imageOptions: ['https://example.com/apple.jpg', 'https://example.com/banana.jpg', 'https://example.com/orange.jpg', 'https://example.com/pear.jpg'],
          pronunciationOptions: [
            { image: 'https://example.com/apple.jpg', word: 'apple' },
            { image: 'https://example.com/banana.jpg', word: 'banana' },
            { image: 'https://example.com/orange.jpg', word: 'orange' },
            { image: 'https://example.com/pear.jpg', word: 'pear' }
          ]
        },
        {
          word: 'banana',
          phonetic: 'bəˈnænə',
          meaning: '香蕉',
          example: 'The monkey likes bananas.',
          image: 'https://example.com/banana.jpg',
          imageOptions: ['https://example.com/banana.jpg', 'https://example.com/apple.jpg', 'https://example.com/orange.jpg', 'https://example.com/pear.jpg'],
          pronunciationOptions: [
            { image: 'https://example.com/banana.jpg', word: 'banana' },
            { image: 'https://example.com/apple.jpg', word: 'apple' },
            { image: 'https://example.com/orange.jpg', word: 'orange' },
            { image: 'https://example.com/pear.jpg', word: 'pear' }
          ]
        }
      ]
    };
    
    // 默认返回动物主题的单词数据
    return wordDataMap[unitId] || wordDataMap['1'];
  }
});